<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="change" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(obj, index) in goodList" :key="index">
          <td>
            <input type="checkbox" v-model="obj.checked" />
          </td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.price }}</td>
          <td>
            <button @click="jian(index)">-</button>
            {{ obj.num }}
            <button @click="add(index)">+</button>
          </td>
          <td>{{ obj.price * obj.num }}</td>
          <td>
            <button @click="del(index)">删除</button>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{ sum }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import { mapState,mapMutations } from 'vuex';
export default {
  // methods: {
  //   ...mapMutations(['ADD']),
  //   ...mapMutations(['JIAN']),
  //   ...mapMutations(['DEL'])
  // },
  methods: {
    jian(index) {
      this.$store.commit('JIAN', index)
    },
    add(index) {
      this.$store.commit('ADD', index)
    },
    del(index) {
      this.$store.commit('DEL', index)
    }
  },

  computed: {
    ...mapState(['goodList']),
    change: {
      set(val) {
        this.$store.state.goodList.forEach(item => item.checked = val)
      },
      get() {
        return this.$store.state.goodList.every(item => item.checked)
      },
    },
    sum() {
      return this.$store.state.goodList.reduce((prev, item) => {
        if (item.checked) {
          return prev + item.num * item.price
        } else {
          return prev
        }
      }, 0)
    }
  },
};
</script>

<style>
</style>